import React, { Component, useEffect, useState, useRef } from "react";
import "./style/style.less";
import { Avatar, Space, Form, Input, Button } from "antd";
import {
  SortableContainer,
  SortableElement,
  SortableHandle,
} from "react-sortable-hoc";
import {
  MenuOutlined,
  EditOutlined,
  SettingOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import TheButton from "@/components/TheButton";
import {
  apiServiceClassifyList,
  apiServiceClassifyEdit,
  apiServiceClassifySort,
  apiServiceClassifyAdd,
  apiServiceClassifyDel
} from "@/request/services";
import arrayMove from "array-move";
import TheDialog from "@/components/TheDialog";
import TheUpload from "@/components/TheUpload";
import TheQuill from "@/components/TheQuill";
import { filtering } from "@/utils/regexp";
import _ from 'lodash'
import _connect from '@/_connect'
const DragHandler = SortableHandle(() => (
  <TheButton  haspermi={['service:category:update']}  ><MenuOutlined style={{ cursor: "grab", color: "#999" }} /></TheButton>

));

const SortableItem = SortableElement(
  ({ value, onEdit, onDelete }) => {
    return (
      <div className={"category-card"}>
        {value.serviceClassifySort !== "1" && <DragHandler />}
        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          {/* <EditOutlined
            onClick={() => onEdit(value)}
            style={{ cursor: "pointer", position: "unset", marginRight: 15 }}
          />
          {value.serviceClassifySort !== "1" && <DeleteOutlined
            onClick={() => onDelete(value)}
            style={{ cursor: "pointer", position: "unset" }}
          />} */}
        </div>
        <div className={"category-content"}>
          <Avatar
            size={80}
            src={value.serviceClassifyImage}
          />
          <span>{value.serviceClassifyName}</span>
        </div>
      </div>
    );
  }
);

const SortableList = SortableContainer(({ children }) => {
  return <>{children}</>;
});

const EditForm = ({ value, dialogCancel, onFinish, editType, btnLoading }) => {
  const formRef = useRef();
  const [classifyFile, setClassifyFile] = useState([]);
  const [bannerFile, setBannerFile] = useState([]);
  useEffect(() => {
    if (value.serviceClassifyId) {
      formRef.current.setFieldsValue({
        serviceClassifyName: value.serviceClassifyName,
        serviceClassifyImage: value.serviceClassifyImage,
        serviceClassifyBannerImage: value.serviceClassifyBannerImage,
        classifyBannerContent: value.classifyBannerContent,
      });
      setBannerFile([
        {
          uid: value.serviceClassifyBannerImage,
          name: "image",
          url: value.serviceClassifyBannerImage,
        },
      ]);
      setClassifyFile([
        {
          uid: value.serviceClassifyImage,
          name: "image",
          url: value.serviceClassifyImage,
        },
      ]);
    }
  }, []);
  /**
   * @desc 设置新闻内容表单默认值
   * */
  const setNewsContent = (data) => {
    formRef.current.setFieldsValue({ classifyBannerContent: data });
  };
  const getClassifyFileResult = (value) => {
    if (value.length && value[0] && value[0].response) {
      formRef.current.setFieldsValue({ serviceClassifyImage: value[0].response.data });
    } else {
      formRef.current.setFieldsValue({ serviceClassifyImage: '' });
    }
  };
  const getBannerFileResult = (value) => {
    if (value.length && value[0] && value[0].response) {
      formRef.current.setFieldsValue({ serviceClassifyBannerImage: value[0].response.data });
    } else {
      formRef.current.setFieldsValue({ serviceClassifyBannerImage: '' });
    }
  };
  const onClose = (data) => {
    data.serviceClassifyId = value.serviceClassifyId;
    data.serviceClassifySort = value.serviceClassifySort;
    onFinish(data);
  };
  return (
    <Form ref={formRef} onFinish={onClose}>
      <Form.Item
        rules={[
          { required: true },
          { max: 6 },
          { pattern: filtering, message: "名称不允许输入特殊字符或空格" },
        ]}
        name={"serviceClassifyName"}
        label={"名称"}
      >
        <Input maxLength={6} />
      </Form.Item>
      {editType === 'add' && <Form.Item
        rules={[{ required: true }]}
        name={"serviceClassifyImage"}
        label={"上传图标"}
      >
        <TheUpload
            isConversion={false}
          // label={"建议尺寸 80*80"}
          maxSize={10}
          fileList={classifyFile}
          getFileResult={getClassifyFileResult}
          len={1}
        />
      </Form.Item>}
      {editType !== 'add' && <Form.Item
        rules={[{ required: true }]}
        name={"serviceClassifyImage"}
        label={"上传图标"}
      >
        {classifyFile.length && (
          <TheUpload
              isConversion={false}
              maxSize={10}
            // label={"建议尺寸 80*80"}
            fileList={classifyFile}
            getFileResult={getClassifyFileResult}
            len={1}
          />
        )}
      </Form.Item>}
      {editType === 'add' && <Form.Item
        rules={[{ required: true }]}
        name={"serviceClassifyBannerImage"}
        label={"上传广告图"}
      >
        <TheUpload
            isConversion={false}
            maxSize={10}
          // label={"建议尺寸 700*280"}
          fileList={bannerFile}
          getFileResult={getBannerFileResult}
          len={1}
        />
      </Form.Item>}
      {editType !== 'add' && <Form.Item
        rules={[{ required: true }]}
        name={"serviceClassifyBannerImage"}
        label={"上传广告图"}
      >
        {bannerFile.length && (
          <TheUpload
              isConversion={false}
              maxSize={10}
            // label={"建议尺寸 700*280"}
            fileList={bannerFile}
            getFileResult={getBannerFileResult}
            len={1}
          />
        )}
      </Form.Item>}
      <Form.Item
        rules={[{ required: true }]}
        name={"classifyBannerContent"}
        label={"广告图详情"}
      >
        <TheQuill
          defaultValue={value.classifyBannerContent || " "}
          setNewsContent={setNewsContent}
        />
      </Form.Item>
      <Form.Item>
        <Space style={{ display: "flex", justifyContent: "flex-end" }}>
          <Button onClick={dialogCancel}>取消</Button>
          <Button loading={btnLoading} type={"primary"} htmlType={"submit"}>
            保存
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

class Category extends Component {
  state = {
    dataSource: [],
    mallData: [],
    title: "",
    dialogStatus: false,
    editValue: null,
    editMode: false,
    editType: "",
    btnLoading: false,
    classifyJson: "",
    len: 0
  };

  async componentDidMount() {
    await this.getData()
  }

  getData = async () => {
    const response = await apiServiceClassifyList();
    if (response.code === 0) {
      const dataSource = response.data.filter((v, i) => v.serviceClassifySort !== 1);
      const mallData = response.data.filter((v, i) => v.serviceClassifySort === 1);
      this.setState({
        dataSource,
        mallData,
        len: response.data.length
      });
    }
  };
  onSortEnd = ({ oldIndex, newIndex }) => {
    this.setState(
      ({ dataSource }) => ({
        dataSource: arrayMove(dataSource, oldIndex, newIndex),
      }),
      () => {
        const dataSource = this.state.dataSource.map((v, i) => {
          return {
            ...v,
            serviceClassifySort: i + 2,
          };
        });
        const classifyJson = JSON.stringify(dataSource);
        this.setState({
          dataSource,
          classifyJson,
        }, async () => {
          await apiServiceClassifySort({ classifyJson: this.state.classifyJson })
          this.getData()
        });
      }
    );
  };
  onEdit = (value, type) => {
    this.setState({
      dialogStatus: true,
      editValue: value,
      editType: type,
      title: '修改类目'
    });
  };
  onDelete = (value) => {
    React.$confirm({
      title: `您确定删除名称为${value.serviceClassifyName}的服务类目吗？`,
      onOk: async () => {
        await apiServiceClassifyDel({ serviceClassifyId: value.serviceClassifyId })
        this.getData()
      },
    });
  };
  onAdd = () => {
    this.setState({
      dialogStatus: true,
      editValue: {},
      editType: 'add',
      title: '新增类目'
    });
  }
  dialogCancel = () => {
    this.setState({
      title: "",
      dialogStatus: false,
      editValue: null,
      editType: ''
    });
  };
  onFinish = async (value) => {
    const keys = Object.keys(value);
    const { editType } = this.state
    keys.forEach((v) => {
      if (!value[v]) {
        delete value[v];
      }
    });
    this.setState({
      btnLoading: true,
    });

    if (editType === 'add') {
      const res = await apiServiceClassifyAdd({ ...value, serviceClassifySort: this.state.len + 1 })
      if (res.code === 0) {
        await this.getData();
        this.dialogCancel();
        React.$message({
          type: "info",
          content: "新增成功",
        });
        this.setState({
          btnLoading: false,
        });
      } else {
        this.setState({
          btnLoading: false,
        });
      }
    } else {
      const response = await apiServiceClassifyEdit({ ...value });
      if (response.code === 0) {
        await this.getData();
        this.dialogCancel();
        React.$message({
          type: "info",
          content: "修改成功",
        });
        this.setState({
          btnLoading: false,
        });
      } else {
        this.setState({
          btnLoading: false,
        });
      }
    }

  };

  render() {
    const {
      dataSource,
      editMode,
      editValue,
      dialogStatus,
      mallData,
      editType,
      btnLoading,
      title
    } = this.state;
    return (
      <div className={"p-layout-box category"}>
        <div className={"p-layout-content"}>
          <div
            style={{
              display: "flex",
              justifyContent: "flex-end",
              marginBottom: 30,
            }}
          >
            <TheButton
              onClick={this.onAdd}
              haspermi={['service:category:add']}
              size={"middle"}
              type={"default"}
            >
              新增类型
            </TheButton>
          </div>
          <SortableList onSortEnd={this.onSortEnd} axis={"xy"} useDragHandle>
            <div className={"category-card-box"}>
              {!_.isEmpty(mallData) && (
                <div className={"category-card"}>
                  {/* <EditOutlined
                    onClick={() => this.onEdit(mallData[0], "mall")}
                    style={{ cursor: "pointer" }}
                  /> */}
                  <div className={"category-content"}>
                    <Avatar
                      size={80}
                      src={mallData[0].serviceClassifyImage}
                    />
                    <span>{mallData[0].serviceClassifyName}</span>
                  </div>
                </div>
              )}
              {dataSource &&
                dataSource.map((v, i) => {
                  return (
                    <SortableItem
                      editMode={editMode}
                      // onEdit={this.onEdit}
                      // onDelete={this.onDelete}
                      index={i}
                      key={i}
                      value={v}
                    />
                  );
                })}
            </div>
          </SortableList>
          <TheDialog
            title={title}
            visible={dialogStatus}
            footer={null}
            handleCancel={this.dialogCancel}
          >
            <EditForm
              btnLoading={btnLoading}
              editType={editType}
              onFinish={this.onFinish}
              value={editValue}
              dialogCancel={this.dialogCancel}
            />
          </TheDialog>
        </div>
      </div>
    );
  }
}

export default _connect(Category);
